﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;

namespace MethodWorx.CMS.UI.Application
{
    public class JsonArrayModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object model = Activator.CreateInstance(bindingContext.ModelType);

            foreach(var propertyInfo in model.GetType().GetProperties())
            {
                var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + "[" + propertyInfo.Name + "]");
                try
                {
                    model.GetType().InvokeMember(
                        propertyInfo.Name,
                        BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance,
                        null,
                        model,
                        new object [] { result.ConvertTo(propertyInfo.PropertyType) });
                }
                catch (Exception)
                {
                }
            }

            return model;
        }
    }
}